package com.fanketly.funacg2.data.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.FilterMenuItemData
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.repo.AudioRepo


class WorkPagingSource(
    val filterMenuItemData: FilterMenuItemData,
    private val repo: AudioRepo,
) : PagingSource<Int, WorkList.Work>() {
    override fun getRefreshKey(state: PagingState<Int, WorkList.Work>): Int? {
        return state.anchorPosition?.let {
            state.closestPageToPosition(it)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(it)?.nextKey?.minus(1)
        }
    }


    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, WorkList.Work> {
        val page = params.key ?: 1 //当前页，默认第一页
        val pageSize = params.loadSize //每页数据条数
        val repository = repo.getWorkList(
            page,
            pageSize,
            filterMenuItemData.id,
            filterMenuItemData.sort
        ) //获取的数据源
        val works = repository.works
        val previousPage = if (page > 1) page - 1 else null //前一页
        val nextPage = if (works.isNotEmpty() && works.size >= pageSize) page + 1 else null //下一页
        Log.d(TAG, "page=$page size=$pageSize")
        return LoadResult.Page(works, previousPage, nextPage)
    }
}